import * as vscode from 'vscode';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';

/**
 * Webview 视图提供者 - 用于侧边栏面板
 */
export class WebviewViewProvider implements vscode.WebviewViewProvider {
    public static readonly viewType = 'cursorRestorePanel';
    private _view?: vscode.WebviewView;
    private _configWatcher?: vscode.FileSystemWatcher;
    private _context?: vscode.ExtensionContext;

    constructor(private readonly _extensionUri: vscode.Uri, context?: vscode.ExtensionContext) {
        this._context = context;
    }

    public resolveWebviewView(
        webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        _token: vscode.CancellationToken,
    ) {
        this._view = webviewView;

        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [this._extensionUri]
        };

        webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

        // 处理来自 webview 的消息
        webviewView.webview.onDidReceiveMessage(async (message) => {
            await this._handleMessage(message);
        });

        // 加载配置
        this._loadConfig();

        // 开始监听配置文件变化
        this._startWatchingConfig();

        // 视图关闭时清理
        webviewView.onDidDispose(() => {
            this._stopWatchingConfig();
        });
    }

    /**
     * 刷新视图
     */
    public refresh() {
        this._loadConfig();
    }

    /**
     * 处理来自 webview 的消息
     */
    private async _handleMessage(message: any) {
        switch (message.command) {
            case 'saveCard':
                this._saveConfig({ card_code: message.value });
                vscode.window.showInformationMessage('激活码已保存');
                break;

            case 'saveToken':
                this._saveConfig({ token: message.value });
                vscode.window.showInformationMessage('Token已保存');
                break;

            case 'privilege':
                await this._executePrivilege();
                break;

            case 'renewal':
                await this._executeRenewal();
                break;

            case 'loadConfig':
                this._loadConfig();
                break;
        }
    }

    /**
     * 加载配置并发送到 webview
     */
    private _loadConfig() {
        const config = this._getConfig();
        this._view?.webview.postMessage({
            command: 'loadConfig',
            config: config
        });
    }

    /**
     * 执行一键特权
     */
    private async _executePrivilege() {
        const config = this._getConfig();
        if (!config.card_code) {
            vscode.window.showWarningMessage('请先输入激活码');
            this._view?.webview.postMessage({
                command: 'privilegeResult',
                success: false,
                message: '请先输入激活码'
            });
            return;
        }

        vscode.window.showInformationMessage('正在执行一键特权...');
        // TODO: 调用 core.js 中的 activatePrivilege 方法

        // 模拟异步操作
        setTimeout(() => {
            this._view?.webview.postMessage({
                command: 'privilegeResult',
                success: true,
                message: '一键特权功能开发中...'
            });
        }, 1000);
    }

    /**
     * 执行一键续杯
     */
    private async _executeRenewal() {
        const config = this._getConfig();
        if (!config.token) {
            vscode.window.showWarningMessage('请先输入Token');
            this._view?.webview.postMessage({
                command: 'renewalResult',
                success: false,
                message: '请先输入Token'
            });
            return;
        }

        vscode.window.showInformationMessage('正在执行一键续杯...');
        // TODO: 调用 core.js 中的 executeRenewal 方法

        // 模拟异步操作
        setTimeout(() => {
            this._view?.webview.postMessage({
                command: 'renewalResult',
                success: true,
                message: '一键续杯功能开发中...'
            });
        }, 1000);
    }

    /**
     * 获取配置
     */
    private _getConfig(): { card_code?: string; token?: string } {
        const configPath = this._getConfigPath();
        if (fs.existsSync(configPath)) {
            try {
                return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
            } catch (error) {
                console.error('读取配置文件失败:', error);
            }
        }
        return {};
    }

    /**
     * 保存配置
     */
    private _saveConfig(newConfig: { card_code?: string; token?: string }): void {
        const configPath = this._getConfigPath();
        const configDir = path.dirname(configPath);

        // 确保目录存在
        if (!fs.existsSync(configDir)) {
            fs.mkdirSync(configDir, { recursive: true });
        }

        // 读取现有配置
        let config: any = {};
        if (fs.existsSync(configPath)) {
            try {
                config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
            } catch (error) {
                console.error('读取配置文件失败:', error);
            }
        }

        // 合并新配置
        config = { ...config, ...newConfig };

        // 保存配置
        fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');

        // 保存后立即重新加载配置并更新页面
        setTimeout(() => {
            this._loadConfig();
        }, 100);
    }

    /**
     * 获取配置文件路径
     */
    private _getConfigPath(): string {
        const homeDir = os.homedir();
        return path.join(homeDir, 'cursor-restore', 'config.json');
    }

    /**
     * 开始监听配置文件变化
     */
    private _startWatchingConfig() {
        const configPath = this._getConfigPath();

        // 创建文件监听器
        this._configWatcher = vscode.workspace.createFileSystemWatcher(
            new vscode.RelativePattern(path.dirname(configPath), path.basename(configPath))
        );

        // 监听文件变化
        this._configWatcher.onDidChange(() => {
            this._loadConfig();
        });

        // 监听文件创建
        this._configWatcher.onDidCreate(() => {
            this._loadConfig();
        });

        // 将监听器添加到订阅中（如果有 context）
        if (this._context) {
            this._context.subscriptions.push(this._configWatcher);
        }
    }

    /**
     * 停止监听配置文件变化
     */
    private _stopWatchingConfig() {
        if (this._configWatcher) {
            this._configWatcher.dispose();
            this._configWatcher = undefined;
        }
    }

    /**
     * 获取 HTML 内容
     */
    private _getHtmlForWebview(webview: vscode.Webview) {
        return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cursor Restore</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            padding: 16px;
            background: var(--vscode-sideBar-background);
            color: var(--vscode-sideBar-foreground);
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--vscode-panel-border);
        }

        .header h1 {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 6px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .header p {
            color: var(--vscode-descriptionForeground);
            font-size: 12px;
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            font-size: 13px;
            color: var(--vscode-input-foreground);
        }

        .form-group label .icon {
            margin-right: 4px;
        }

        .form-group input {
            width: 100%;
            padding: 8px 10px;
            background: var(--vscode-input-background);
            color: var(--vscode-input-foreground);
            border: 1px solid var(--vscode-input-border);
            border-radius: 4px;
            font-size: 13px;
            transition: all 0.2s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: var(--vscode-focusBorder);
            box-shadow: 0 0 0 2px var(--vscode-focusBorder)33;
        }

        .form-group input::placeholder {
            color: var(--vscode-input-placeholderForeground);
        }

        .button-group {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 20px;
        }

        .btn {
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-secondary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        .status {
            margin-top: 16px;
            padding: 10px 12px;
            border-radius: 4px;
            font-size: 12px;
            display: none;
        }

        .status.success {
            background: var(--vscode-testing-iconPassed)22;
            color: var(--vscode-testing-iconPassed);
            border-left: 3px solid var(--vscode-testing-iconPassed);
        }

        .status.error {
            background: var(--vscode-testing-iconFailed)22;
            color: var(--vscode-testing-iconFailed);
            border-left: 3px solid var(--vscode-testing-iconFailed);
        }

        .status.info {
            background: var(--vscode-testing-iconQueued)22;
            color: var(--vscode-testing-iconQueued);
            border-left: 3px solid var(--vscode-testing-iconQueued);
        }

        .footer {
            margin-top: 20px;
            text-align: center;
            color: var(--vscode-descriptionForeground);
            font-size: 11px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .spinning {
            animation: spin 1s linear infinite;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🔄 Cursor Restore</h1>
        <p>轻松管理激活和续杯</p>
    </div>

    <form id="configForm">
        <div class="form-group">
            <label for="cardInput">
                <span class="icon">🔑</span>
                激活码
            </label>
            <input
                type="text"
                id="cardInput"
                placeholder="请输入激活码"
                autocomplete="off"
            />
        </div>

        <div class="form-group">
            <label for="tokenInput">
                <span class="icon">🔐</span>
                Token
            </label>
            <input
                type="text"
                id="tokenInput"
                placeholder="请输入Token"
                autocomplete="off"
            />
        </div>

        <div class="button-group">
            <button type="button" class="btn btn-primary" id="privilegeBtn">
                <span>⭐</span>
                <span>一键特权</span>
            </button>
            <button type="button" class="btn btn-secondary" id="renewalBtn">
                <span>🔄</span>
                <span>一键续杯</span>
            </button>
        </div>
    </form>

    <div id="status" class="status"></div>

    <div class="footer">
        <p>配置自动保存</p>
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        const cardInput = document.getElementById('cardInput');
        const tokenInput = document.getElementById('tokenInput');
        const privilegeBtn = document.getElementById('privilegeBtn');
        const renewalBtn = document.getElementById('renewalBtn');
        const statusDiv = document.getElementById('status');

        // 显示状态消息
        function showStatus(message, type = 'info') {
            statusDiv.textContent = message;
            statusDiv.className = 'status ' + type;
            statusDiv.style.display = 'block';

            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }

        // 保存激活码
        cardInput.addEventListener('blur', () => {
            const value = cardInput.value.trim();
            if (value) {
                vscode.postMessage({
                    command: 'saveCard',
                    value: value
                });
            }
        });

        // 保存 Token
        tokenInput.addEventListener('blur', () => {
            const value = tokenInput.value.trim();
            if (value) {
                vscode.postMessage({
                    command: 'saveToken',
                    value: value
                });
            }
        });

        // 一键特权
        privilegeBtn.addEventListener('click', () => {
            if (!cardInput.value.trim()) {
                showStatus('请先输入激活码', 'error');
                cardInput.focus();
                return;
            }

            privilegeBtn.disabled = true;
            const icon = privilegeBtn.querySelector('span:first-child');
            icon.classList.add('spinning');

            vscode.postMessage({ command: 'privilege' });
        });

        // 一键续杯
        renewalBtn.addEventListener('click', () => {
            if (!tokenInput.value.trim()) {
                showStatus('请先输入 Token', 'error');
                tokenInput.focus();
                return;
            }

            renewalBtn.disabled = true;
            const icon = renewalBtn.querySelector('span:first-child');
            icon.classList.add('spinning');

            vscode.postMessage({ command: 'renewal' });
        });

        // 接收来自扩展的消息
        window.addEventListener('message', event => {
            const message = event.data;

            switch (message.command) {
                case 'loadConfig':
                    if (message.config.card_code) {
                        cardInput.value = message.config.card_code;
                    }
                    if (message.config.token) {
                        tokenInput.value = message.config.token;
                    }
                    break;

                case 'privilegeResult':
                    privilegeBtn.disabled = false;
                    privilegeBtn.querySelector('span:first-child').classList.remove('spinning');
                    showStatus(message.message, message.success ? 'success' : 'error');
                    break;

                case 'renewalResult':
                    renewalBtn.disabled = false;
                    renewalBtn.querySelector('span:first-child').classList.remove('spinning');
                    showStatus(message.message, message.success ? 'success' : 'error');
                    break;
            }
        });

        // 页面加载时请求配置
        vscode.postMessage({ command: 'loadConfig' });
    </script>
</body>
</html>`;
    }
}